<script setup lang="ts">
import { reactive, ref } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

// 接口定义
interface UltrasoundOrder {
  id: string;
  orderName: string;
  petName: string;
  ownerName: string;
  requestDoctor: string;
  createTime: string;
  status: 'completed' | 'pending' | 'processing';
}

interface UltrasoundImage {
  id: string;
  name: string;
  url: string;
  saveTime: string;
}

interface ReportData {
  examPart: string;
  examDoctor: string;
  examTime: any;
  images: UltrasoundImage[];
  ultrasoundFindings: string;
  ultrasoundDiagnosis: string;
  remarks: string;
}

interface Measurement {
  depth: number;
  gain: number;
  frequency: number;
}

// 响应式数据
const selectedOrder = ref<null | UltrasoundOrder>(null);
const isConnected = ref(false);
const isRecording = ref(false);
const currentImage = ref(
  'https://via.placeholder.com/600x400/87CEEB/000000?text=Ultrasound+Image',
);

const measurement = reactive<Measurement>({
  depth: 10,
  gain: 50,
  frequency: 5,
});

const reportData = reactive<ReportData>({
  examPart: '',
  examDoctor: '',
  examTime: null,
  images: [],
  ultrasoundFindings: '',
  ultrasoundDiagnosis: '',
  remarks: '',
});

// 模拟B超检验单数据
const ultrasoundOrders = ref<UltrasoundOrder[]>([
  {
    id: '1',
    orderName: `US${dayjs().format('YYYYMMDD')}001`,
    petName: '小白',
    ownerName: '张三',
    requestDoctor: '李医生',
    createTime: dayjs().subtract(2, 'hour').format('YYYY-MM-DD HH:mm:ss'),
    status: 'completed',
  },
  {
    id: '2',
    orderName: `US${dayjs().format('YYYYMMDD')}002`,
    petName: '咪咪',
    ownerName: '李四',
    requestDoctor: '王医生',
    createTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
    status: 'processing',
  },
]);

// 方法
const createUltrasoundOrder = () => {
  const newOrder: UltrasoundOrder = {
    id: Date.now().toString(),
    orderName: `US${dayjs().format(
      'YYYYMMDD',
    )}${String(ultrasoundOrders.value.length + 1).padStart(3, '0')}`,
    petName: '新宠物',
    ownerName: '新主人',
    requestDoctor: '当前医生',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
  };

  ultrasoundOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('B超检验单创建成功！');
};

const selectOrder = (order: UltrasoundOrder) => {
  selectedOrder.value = order;
  loadReportData(order.id);
};

const loadReportData = (orderId: string) => {
  if (orderId === '1') {
    reportData.examPart = 'abdomen';
    reportData.examDoctor = '张技师';
    reportData.examTime = dayjs().subtract(1, 'hour');
    reportData.ultrasoundFindings =
      '肝脏大小正常，回声均匀，胆囊大小正常，壁光滑。';
    reportData.ultrasoundDiagnosis = '腹部B超检查未见明显异常。';
    reportData.remarks = '建议定期复查。';
    reportData.images = [
      {
        id: '1',
        name: '腹部B超图像1',
        url: 'https://via.placeholder.com/300x400/87CEEB/000000?text=Abdomen+US1',
        saveTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      },
    ];
  } else {
    Object.assign(reportData, {
      examPart: '',
      examDoctor: '',
      examTime: null,
      images: [],
      ultrasoundFindings: '',
      ultrasoundDiagnosis: '',
      remarks: '',
    });
  }
};

const connectDevice = () => {
  isConnected.value = !isConnected.value;
  if (isConnected.value) {
    message.success('B超设备连接成功！');
    startImageUpdate();
  } else {
    message.info('B超设备已断开连接');
  }
};

const startImageUpdate = () => {
  if (!isConnected.value) return;

  const interval = setInterval(() => {
    if (!isConnected.value) {
      clearInterval(interval);
      return;
    }

    const timestamp = Date.now();
    currentImage.value = `https://via.placeholder.com/600x400/87CEEB/000000?text=Ultrasound+${timestamp}`;
  }, 1000);
};

const captureImage = () => {
  if (!isConnected.value) {
    message.warning('请先连接设备');
    return;
  }

  message.success('图像已截图');
};

const startRecording = () => {
  if (!isConnected.value) {
    message.warning('请先连接设备');
    return;
  }

  isRecording.value = !isRecording.value;
  message.success(isRecording.value ? '开始录制' : '停止录制');
};

const saveCurrentImage = () => {
  if (!isConnected.value) {
    message.warning('请先连接设备');
    return;
  }

  const newImage: UltrasoundImage = {
    id: Date.now().toString(),
    name: `B超图像_${dayjs().format('YYYYMMDD_HHmmss')}`,
    url: currentImage.value,
    saveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };

  reportData.images.push(newImage);
  message.success('图像已保存');
};

const viewImageGallery = () => {
  message.info('图像库功能开发中...');
};

const removeImage = (index: number) => {
  reportData.images.splice(index, 1);
  message.success('图像已删除');
};

const saveReport = () => {
  if (!selectedOrder.value) {
    message.warning('请先选择检验单');
    return;
  }

  if (!reportData.examPart) {
    message.warning('请选择检查部位');
    return;
  }

  if (!reportData.examDoctor) {
    message.warning('请填写检查医生');
    return;
  }

  if (!reportData.ultrasoundFindings) {
    message.warning('请填写B超表现');
    return;
  }

  if (!reportData.ultrasoundDiagnosis) {
    message.warning('请填写B超诊断');
    return;
  }

  selectedOrder.value.status = 'completed';
  message.success('B超检查报告保存成功！');
};

const printReport = () => {
  message.success('打印功能已触发');
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待检查',
    processing: '检查中',
    completed: '已完成',
  };
  return textMap[status] || status;
};
</script>

<template>
  <div class="ultrasound-management">
    <!-- 左侧：检验单列表 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>B超检验单</h3>
        <a-button type="primary" size="small" @click="createUltrasoundOrder">
          + 新建检验单
        </a-button>
      </div>

      <div class="order-list">
        <div
          v-for="order in ultrasoundOrders"
          :key="order.id"
          class="order-item"
          :class="{ active: selectedOrder?.id === order.id }"
          @click="selectOrder(order)"
        >
          <div class="order-info">
            <div class="order-name">{{ order.orderName }}</div>
            <div class="pet-info">
              {{ order.petName }}({{ order.ownerName }})
            </div>
            <div class="order-time">{{ order.createTime }}</div>
          </div>
          <div class="order-status">
            <a-tag :color="getStatusColor(order.status)">
              {{ getStatusText(order.status) }}
            </a-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间：实时图像显示 -->
    <div class="center-panel">
      <div class="ultrasound-display">
        <div class="display-header">
          <h3>实时图像显示</h3>
          <div class="display-controls">
            <a-button type="default" size="small" @click="connectDevice">
              🔌 连接设备
            </a-button>
            <a-button type="default" size="small" @click="captureImage">
              📸 截图
            </a-button>
            <a-button type="default" size="small" @click="startRecording">
              🎥 {{ isRecording ? '停止录制' : '开始录制' }}
            </a-button>
          </div>
        </div>

        <div class="display-area">
          <div v-if="isConnected" class="ultrasound-view">
            <div class="ultrasound-screen">
              <div class="screen-content">
                <div class="ultrasound-image">
                  <img :src="currentImage" alt="B超图像" />
                </div>
                <div class="ultrasound-overlay">
                  <div class="measurement-info">
                    <div class="info-item">深度: {{ measurement.depth }}cm</div>
                    <div class="info-item">增益: {{ measurement.gain }}dB</div>
                    <div class="info-item">
                      频率: {{ measurement.frequency }}MHz
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="control-panel">
              <div class="control-group">
                <span class="control-label">深度调节:</span>
                <a-slider
                  v-model:value="measurement.depth"
                  :min="5"
                  :max="20"
                  style="width: 150px"
                />
              </div>
              <div class="control-group">
                <span class="control-label">增益调节:</span>
                <a-slider
                  v-model:value="measurement.gain"
                  :min="0"
                  :max="100"
                  style="width: 150px"
                />
              </div>
              <div class="control-group">
                <span class="control-label">频率选择:</span>
                <a-select
                  v-model:value="measurement.frequency"
                  style="width: 120px"
                  size="small"
                >
                  <a-select-option value="3.5">3.5MHz</a-select-option>
                  <a-select-option value="5.0">5.0MHz</a-select-option>
                  <a-select-option value="7.5">7.5MHz</a-select-option>
                  <a-select-option value="10.0">10.0MHz</a-select-option>
                </a-select>
              </div>
            </div>
          </div>

          <div v-else class="disconnected-state">
            <div class="disconnected-icon">🔌</div>
            <div class="disconnected-text">设备未连接</div>
            <div class="disconnected-hint">请先连接B超设备</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：检查报告 -->
    <div class="right-panel">
      <div v-if="selectedOrder" class="report-section">
        <div class="report-header">
          <h3>B超检查报告</h3>
          <div class="header-actions">
            <a-button
              type="default"
              @click="printReport"
              style="margin-right: 8px"
            >
              🖨️ 打印
            </a-button>
            <a-button type="primary" @click="saveReport">保存</a-button>
          </div>
        </div>

        <div class="report-form">
          <!-- 基本信息 -->
          <div class="form-section">
            <h4>基本信息</h4>
            <div class="form-grid">
              <div class="form-item">
                <span class="label">检验单号：</span>
                <span class="value">{{ selectedOrder.orderName }}</span>
              </div>
              <div class="form-item">
                <span class="label">宠物名称：</span>
                <span class="value">{{ selectedOrder.petName }}</span>
              </div>
              <div class="form-item">
                <span class="label">主人姓名：</span>
                <span class="value">{{ selectedOrder.ownerName }}</span>
              </div>
              <div class="form-item">
                <span class="label">申请医生：</span>
                <span class="value">{{ selectedOrder.requestDoctor }}</span>
              </div>
            </div>
          </div>

          <!-- 检查信息 -->
          <div class="form-section">
            <h4>检查信息</h4>
            <div class="form-grid">
              <div class="form-item">
                <span class="label">检查部位：</span>
                <a-select
                  v-model:value="reportData.examPart"
                  style="width: 200px"
                  placeholder="请选择检查部位"
                >
                  <a-select-option value="abdomen">腹部</a-select-option>
                  <a-select-option value="heart">心脏</a-select-option>
                  <a-select-option value="liver">肝脏</a-select-option>
                  <a-select-option value="kidney">肾脏</a-select-option>
                  <a-select-option value="bladder">膀胱</a-select-option>
                  <a-select-option value="uterus">子宫</a-select-option>
                </a-select>
              </div>
              <div class="form-item">
                <span class="label">检查医生：</span>
                <a-input
                  v-model:value="reportData.examDoctor"
                  style="width: 200px"
                  placeholder="请输入检查医生"
                />
              </div>
              <div class="form-item">
                <span class="label">检查时间：</span>
                <a-date-picker
                  v-model:value="reportData.examTime"
                  show-time
                  style="width: 200px"
                  placeholder="请选择检查时间"
                />
              </div>
            </div>
          </div>

          <!-- 图像存储 -->
          <div class="form-section">
            <h4>图像存储</h4>
            <div class="image-storage">
              <div class="storage-actions">
                <a-button type="primary" @click="saveCurrentImage">
                  💾 保存当前图像
                </a-button>
                <a-button type="default" @click="viewImageGallery">
                  🖼️ 查看图库
                </a-button>
              </div>

              <div class="image-gallery">
                <div
                  v-for="(image, index) in reportData.images"
                  :key="index"
                  class="image-item"
                >
                  <div class="image-container">
                    <img :src="image.url" :alt="image.name" />
                    <div class="image-overlay">
                      <a-button
                        type="text"
                        size="small"
                        danger
                        @click="removeImage(index)"
                      >
                        ×
                      </a-button>
                    </div>
                  </div>
                  <div class="image-info">
                    <div class="image-name">{{ image.name }}</div>
                    <div class="image-time">{{ image.saveTime }}</div>
                  </div>
                </div>

                <div v-if="reportData.images.length === 0" class="empty-images">
                  <div class="empty-icon">🖼️</div>
                  <div class="empty-text">暂无保存的图像</div>
                </div>
              </div>
            </div>
          </div>

          <!-- B超表现 -->
          <div class="form-section">
            <h4>B超表现</h4>
            <a-textarea
              v-model:value="reportData.ultrasoundFindings"
              :rows="4"
              placeholder="请描述B超表现..."
            />
          </div>

          <!-- B超诊断 -->
          <div class="form-section">
            <h4>B超诊断</h4>
            <a-textarea
              v-model:value="reportData.ultrasoundDiagnosis"
              :rows="4"
              placeholder="请填写B超诊断..."
            />
          </div>

          <!-- 备注 -->
          <div class="form-section">
            <h4>备注</h4>
            <a-textarea
              v-model:value="reportData.remarks"
              :rows="3"
              placeholder="请填写备注信息..."
            />
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">请选择B超检验单查看报告</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.ultrasound-management {
  display: flex;
  height: 100%;
  background: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 320px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.order-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.order-item {
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.order-item:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.order-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.order-info {
  margin-bottom: 8px;
}

.order-name {
  margin-bottom: 4px;
  font-weight: bold;
  color: #333;
}

.pet-info {
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.center-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: white;
}

.ultrasound-display {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.display-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
}

.display-header h3 {
  margin: 0;
  color: #333;
}

.display-controls {
  display: flex;
  gap: 8px;
}

.display-area {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 24px;
}

.ultrasound-view {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 16px;
}

.ultrasound-screen {
  position: relative;
  flex: 1;
  overflow: hidden;
  background: #000;
  border: 2px solid #333;
  border-radius: 8px;
}

.screen-content {
  position: relative;
  width: 100%;
  height: 100%;
}

.ultrasound-image {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.ultrasound-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.ultrasound-overlay {
  position: absolute;
  top: 16px;
  right: 16px;
  padding: 8px;
  font-size: 12px;
  color: white;
  background: rgb(0 0 0 / 70%);
  border-radius: 4px;
}

.measurement-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item {
  color: #fff;
}

.control-panel {
  display: flex;
  gap: 24px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 6px;
}

.control-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.control-label {
  min-width: 60px;
  font-size: 12px;
  color: #666;
}

.disconnected-state {
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.disconnected-icon {
  margin-bottom: 16px;
  font-size: 64px;
}

.disconnected-text {
  margin-bottom: 8px;
  font-size: 18px;
}

.disconnected-hint {
  font-size: 14px;
}

.right-panel {
  display: flex;
  flex-direction: column;
  width: 400px;
  background: white;
  border-left: 1px solid #e8e8e8;
}

.report-section {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.report-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
}

.report-header h3 {
  margin: 0;
  color: #333;
}

.report-form {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
}

.form-section h4 {
  margin: 0 0 16px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.form-item {
  display: flex;
  align-items: center;
}

.form-item .label {
  width: 100px;
  font-size: 14px;
  color: #666;
}

.form-item .value {
  flex: 1;
  font-weight: bold;
  color: #333;
}

.image-storage {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.storage-actions {
  display: flex;
  gap: 8px;
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  min-height: 200px;
}

.image-item {
  overflow: hidden;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.image-container {
  position: relative;
  height: 120px;
  overflow: hidden;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.image-info {
  padding: 8px;
}

.image-name {
  margin-bottom: 4px;
  font-size: 12px;
  color: #333;
}

.image-time {
  font-size: 10px;
  color: #999;
}

.empty-images {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

.empty-icon {
  margin-bottom: 8px;
  font-size: 48px;
}

.empty-text {
  font-size: 14px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-state .empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-state .empty-text {
  font-size: 14px;
}
</style>
